package com.glwan.fixedassetapp.Adapter;


import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;
import java.util.Map;

public class ListableAdapter extends BaseAdapter {

    public List<? extends Map<String, Object>> data;
    public Map<String, Integer> textViewMaps;
    public Integer itemView;
    private View viewCache;
    private LayoutInflater inflater;
    private Integer openStatus = -1;

    /**
     * @param context      conext
     * @param data         列表数据
     * @param textViewMaps 列表数据的textview
     * @param itemView     列表数据的layout_view
     */
    public ListableAdapter(Context context, List<? extends Map<String, Object>> data, Map<String, Integer> textViewMaps, int itemView) {
        inflater = LayoutInflater.from(context);

        this.textViewMaps = textViewMaps;
        this.itemView = itemView;

        this.data = data;
    }

    public void clear() {
        data.clear();
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    public void setOpenStatus(int i) {
        this.openStatus = i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        if (viewCache == view && viewCache != null) {
            view = viewCache;
        } else {
            view = inflater.inflate(itemView, null);
            setTextValue(view, i);

        }

        viewCache = view;

        return view;
    }

    private void setTextValue(View view, int i) {
        for (Map.Entry<String, Integer> textViewMap : textViewMaps.entrySet()) {

            TextView textView = view.findViewById(textViewMap.getValue());

            String key = textViewMap.getKey();
            Log.i("key", key);

            if (("sortNo").equals(key)) {
                textView.setText(String.valueOf(i + 1));
            } else {
                String value = String.valueOf(data.get(i).getOrDefault(key, ""));
                textView.setText(value);
            }
            Context context = view.getContext();
            if (context instanceof ListableAdapterCustomHandler) {
                ((ListableAdapterCustomHandler) context).customHandler(key, textView);
            }
        }
    }

}
